import {
    Token,
    getThis,
    isArray,
    isDef,
    isNullOrUndef
} from "./index.js";
import store from "@/store";

let _this;
// export const baseUrl = "https://8080-xp-test.2ndtool.top";
export const baseUrl = "http://8.152.7.94:18085";
// export const baseUrl = "http://10.19.240.135:18085";


const reqHeader = () => {
    return {
        "content-type": "application/json;charset=utf-8",
        "Authorization": Token.get(),
    };
};

const resolveRes = (resData) => {
    resData.code = Number(resData.code);
    const {
        data,
        code,
        message
    } = resData;
    if (code === 201 || code === 202 || code === 206 || code === 401) {
        uni.showModal({
            title: '提示',
            content: '你已被登出，可以取消继续留在该页面，或者重新登录',
            confirmText: '重新登录',
            cancelText: '取消',
            success: function(res) {
                if (res.confirm) {
                    store.dispatch("logout");
                } else if (res.cancel) {
                    console.log('用户点击取消');
                }
            }
        });
    }
    // 请求失败
    if (code != 200) {
        //提示错误信息
        console.log('response error', data);
        uni.showToast({
            icon: "error",
            title: message,
            duration: 1500
        })
    }
    return resData;
};

export class Request {
    /**
     * config: {
     *   url: '',
     *   method: 'get',
     *   data: {},
     *   params: {},
     *   header: {}
     * }
     * refresh: 是否需要自动刷新token
     */
    static async request(config, refresh = true) {
        _this = getThis();
        // 拼接完整url
        config.url = baseUrl + config.url;
        // 拼接params路径参数
        if (!!config.params) {
            config.url = generateUrl(config.url, config.params);
            Reflect.deleteProperty(config, "params");
        }
        if (config.url.toLowerCase().includes("login")) {
            const headers = reqHeader();
            delete headers.Authorization;  // 删除 Authorization 头
            config.header = headers;
        } else {
            config.header = reqHeader();
        }
        console.log("请求配置： ", config);
        // 请求前刷新token
        if (refresh) await Token.refresh();
        // 发送请求
        let res = await uni.request(config);
        res = res[1];
        console.log("响应结果： ", res);
        // 响应状态码提示
        statusHelper(res.statusCode);
        // 解析响应结果集
        return resolveRes(res.data);
    }

    static get(url, params = undefined, refresh = true) {
        return this.request({
                url: url,
                methos: "get",
                params: params,
            },
            refresh
        );
    }

    static post(url, data = undefined, refresh = true) {
        return this.request({
                url: url,
                method: "post",
                data: data,
            },
            refresh
        );
    }

    static put(url, data = undefined, refresh = true) {
        return this.request({
                url: url,
                method: "put",
                data: data,
            },
            refresh
        );
    }

    static delete(url, params = undefined, refresh = true) {
        return this.request({
                url: url,
                method: "delete",
                params: params,
            },
            refresh
        );
    }

    static async upload(url, filePath, params = undefined) {
        _this = getThis();
        await Token.refresh();

        let res = await uni.uploadFile({
            header: reqHeader(),
            url: baseUrl + url,
            filePath: filePath,
            name: "file",
            formData: params,
        });
        
        res = res[1];
        console.log("上传文件响应结果：", res);

        statusHelper(res.statusCode);

        const resData = JSON.parse(res.data);
        return resolveRes(resData);
    }
}

const generateUrl = (url, params) => {
    if (Object.keys(params).length !== 0) {
        url += "?";
        Object.keys(params).forEach((key) => {
            const value = params[key];
            let partKey = encodeURIComponent(key) + "=";
            if (isArray(value)) {
                value.forEach((item) => {
                    url += partKey + encodeURIComponent(item) + "&";
                });
            } else {
                url += partKey + encodeURIComponent(value) + "&";
            }
        });
        return url.slice(0, -1);
    }
    console.error("请求参数有误", params);
    return "";
};

const statusHelper = (code) => {
    let message;
    switch (code) {
        case 200:
            return;
        case 400:
            message = "请求参数错误";
            break;
        case 401:
            message = "登录已过期";
            store.dispatch("logout");
            break;
        case 403:
            message = "没有权限";
            break;
        case 404:
            message = "资源不存在";
            break;
        case 408:
            message = "请求超时";
            break;
        case 500:
            message = "服务器异常";
            break;
        default:
            message = `【${code}】未知异常!`;
            break;
    }
    uni.showToast({
        icon: "error",
        title: message,
        duration: 1500
    })
};